package org.example.testWebsocket.interceptor;

import org.example.testWebsocket.entity.MyUserInfo;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

@Component
public class WebSocketInterceptor implements HandshakeInterceptor {
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
                                   WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        // 从请求中获取房间id和用户信息
        if (request instanceof ServerHttpRequest) {
            ServletServerHttpRequest serverRequest = (ServletServerHttpRequest) request;
            String roomId = serverRequest.getServletRequest().getParameter("roomId");
            String userId = serverRequest.getServletRequest().getParameter("userId");
            String username = serverRequest.getServletRequest().getParameter("username");

            if (roomId == null || userId == null || username == null) {
                throw new IllegalArgumentException("miss required parameters: roomId,userId,username");
            }
            attributes.put("roomId", roomId);
            attributes.put("user", new MyUserInfo(userId, username));
        }
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }
}
